package com.anxinr.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;

/**
 * JWT工具类
 *
 * @Author anxinr
 */
public class JWTUtils {

    public static String generate(String userName) {
        return Jwts.builder()
                .setSubject(userName)
                .signWith(SignatureAlgorithm.HS512, "study".getBytes())
                .compact();
    }

    /**
     * 解析token
     * @return 用户名
     */
    public static String parserToken(HttpServletRequest request){
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            return null;
        }
        return parseJWT(token);
    }

    /**
     * 解析JWT字符串
     */
    public static String parseJWT(String token) {
        return Jwts.parser()
                .setSigningKey("study".getBytes())
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }
}
